package info.thereisonlywe.onenesspathfinder.ui;

import info.thereisonlywe.core.color.ColorLibrary;
import info.thereisonlywe.core.font.FontLibrary;
import info.thereisonlywe.core.ui.swing.extensions.table.EmptyCellEditor;
import info.thereisonlywe.core.ui.swing.extensions.table.TextAreaRenderer;
import info.thereisonlywe.onenesspathfinder.controllers.RecitationController;
import info.thereisonlywe.quran.Quran;
import info.thereisonlywe.quran.text.QuranicTextList;

import java.awt.Adjustable;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class SectionPane extends JScrollPane {

	private final JTable table_BirdsEyeView = new JTable()
	{
		@Override
		public TableCellRenderer getCellRenderer(int row, int column)
		{
			return getColumnModel().getColumn(0).getCellRenderer();
		}

	};

	public SectionPane()
	{
		super();
		initComponents();
		initListeners();
	}

	public JTable getTable()
	{
		return table_BirdsEyeView;
	}

	private void initComponents()
	{
		table_BirdsEyeView.setRowSorter(null);
		table_BirdsEyeView.setCursor(new Cursor(Cursor.HAND_CURSOR));
		table_BirdsEyeView.setTableHeader(null);
		table_BirdsEyeView.setForeground(ColorLibrary.ROYAL_MAROON);
		table_BirdsEyeView.setBackground(Color.white);
		table_BirdsEyeView
				.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		TableModel model = new TableModel();
		model.addTableModelListener(new TableListener());
		table_BirdsEyeView.setModel(model);
		table_BirdsEyeView.getColumnModel().getColumn(0)
				.setCellRenderer(new TableRenderer());
		table_BirdsEyeView.getColumnModel().getColumn(0)
				.setCellEditor(new EmptyCellEditor());
		table_BirdsEyeView.setSelectionBackground(new Color(242, 242, 242));
		table_BirdsEyeView.setSelectionForeground(Color.black);
		setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		setViewportView(table_BirdsEyeView);
		setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.DARK_GRAY));

		table_BirdsEyeView.getInputMap(
				JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke("ENTER"), "none");
		table_BirdsEyeView.getInputMap(
				JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke("TAB"), "none");
		table_BirdsEyeView.getInputMap(
				JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke("LEFT"), "none");
		table_BirdsEyeView.getInputMap(
				JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke("RIGHT"), "none");
		table_BirdsEyeView.getInputMap(
				JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke("UP"), "none");
		table_BirdsEyeView.getInputMap(
				JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke("DOWN"), "none");
		table_BirdsEyeView.getActionMap().put("none", new AbstractAction()
		{

			@Override
			public void actionPerformed(ActionEvent e)
			{
			}
		});
	}

	private void initListeners()
	{
		table_BirdsEyeView.addMouseListener(new MouseAdapter()
		{

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (UIDelegate.isBrowserLocked()
						&& !RecitationController.getImam().isPaused())
				{
					int rowIndex = UIDelegate.getDisplayedVerse()
							.getVerseNumber() - 1;
					UIDelegate.SectionPaneHook.focusRow(rowIndex);
					return;
				}
				int x = table_BirdsEyeView.rowAtPoint(e.getPoint());
				UIDelegate.seekToVerseInSection(x + 1);
				UIDelegate.refreshVerse();
				UIDelegate.SectionPaneHook.focusRow(x);
			}
		});

		table_BirdsEyeView.addMouseWheelListener(new MouseWheelListener()
		{

			@Override
			public void mouseWheelMoved(MouseWheelEvent e)
			{
				if (!e.isControlDown())
				{
					Adjustable adj = SectionPane.this.getVerticalScrollBar();
					int scroll = e.getUnitsToScroll() * adj.getBlockIncrement();
					adj.setValue(adj.getValue() + scroll);
				}
			}
		});
	}

	private class TableListener implements TableModelListener {
		@Override
		public void tableChanged(TableModelEvent te)
		{
			int pref = QuranicTextList.getPreferred();
			if (pref < 0) table_BirdsEyeView.setFont(FontLibrary.get(
					FontLibrary.SCHERAZADE, Font.BOLD + Font.ITALIC, 24));
			else table_BirdsEyeView.setFont(FontLibrary.get(
					FontLibrary.DROID_SANS, Font.BOLD + Font.ITALIC, 13));
		}
	}

	public class TableModel extends AbstractTableModel {

		private int sectionIndex = 0;
		private int verseCount = 7;

		public TableModel()
		{
		}

		@Override
		public int getRowCount()
		{
			return verseCount;
		}

		@Override
		public int getColumnCount()
		{
			return 1;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex)
		{
			int p = QuranicTextList.getPreferred();
			if (p < 0) return Quran.getVerse(sectionIndex + rowIndex)
					.getContent();
			else return QuranicTextList.getText(p).getVerseContent(
					sectionIndex + rowIndex);
		}

		@Override
		public Class<?> getColumnClass(int columnIndex)
		{
			return String.class;
		}

		public void setSection(int index, int vc)
		{
			this.sectionIndex = index;
			this.verseCount = vc;
			(new UIDelegate.SectionPaneHook.ResetTask()).execute();
		}
	}

	public static class TableRenderer extends TextAreaRenderer {

		private static final TitledBorder border = BorderFactory
				.createTitledBorder(
						BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
						"0", 0, TitledBorder.BOTTOM,
						FontLibrary.get(FontLibrary.DROID_SANS, Font.BOLD, 12),
						Color.black);

		public TableRenderer()
		{
			super();
		}

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object obj, boolean isSelected, boolean hasFocus, int row,
				int column)
		{
			adaptee.getTableCellRendererComponent(table, obj, isSelected,
					hasFocus, row, column);
			int pref = QuranicTextList.getPreferred();
			if (pref == -1 || QuranicTextList.getText(pref).isRTL())
			{
				setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
			}
			else
			{
				setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			}
			setForeground(adaptee.getForeground());
			setBackground(adaptee.getBackground());
			setFont(adaptee.getFont());
			setText(adaptee.getText());
			border.setTitle(String.valueOf((row + 1)));
			border.setTitleJustification(pref == -1
					|| QuranicTextList.getText(pref).isRTL() ? Integer
					.valueOf(TitledBorder.RIGHT) : Integer
					.valueOf(TitledBorder.LEFT));
			setBorder(border);
			TableColumnModel columnModel = table.getColumnModel();
			setSize(columnModel.getColumn(column).getWidth(), 100000);
			int height_wanted = (int) getPreferredSize().getHeight();
			addSize(table, row, column, height_wanted);
			height_wanted = findTotalMaximumRowSize(table, row);
			if (height_wanted != table.getRowHeight(row))
			{
				table.setRowHeight(row, height_wanted);
			}
			return this;
		}

		@Override
		public void invalidate()
		{
		}

		@Override
		public void repaint()
		{
		}
	}

}
